const router = require('koa-router')()
const util = require('../utils/util')
const Dept = require('../models/deptSchema')

router.prefix('/dept')

router.get('/list', async (ctx) => {
  const { deptName } = ctx.request.query
  const params = {}
  if (deptName) params.deptName = deptName
  const rootList = await Dept.find(params)

  if (deptName) {
    ctx.body = util.success(rootList)
  } else {
    const list = getTreeMenu(rootList, null, [])
    ctx.body = util.success(list)
  }
})

function getTreeMenu(rootList, id, list) {
  for (let i = 0; i < rootList.length; i++) {
    let item = rootList[i]
    if (String(item.parentId.slice().pop()) == String(id)) {
      list.push(item._doc)
    }
  }
  list.map((item) => {
    item.children = []
    getTreeMenu(rootList, item._id, item.children)

    if (item.children.length === 0) {
      delete item.children
    }
  })

  return list
}

router.post('/operate', async (ctx) => {
  const { _id, action, ...params } = ctx.request.body
  let res, info
  if (action === 'create') {
    res = await Dept.create(params)
    info = '创建成功'
  } else if (action === 'edit') {
    params.updateTime = new Date()
    res = await Dept.findByIdAndUpdate(_id, params)
    info = '编辑成功'
  } else if (action === 'delete') {
    res = await Dept.findByIdAndRemove(_id)
    await Dept.deleteMany({ parentId: { $all: [_id] } })
    info = '删除成功'
  }
  ctx.body = util.success('', info)
})

module.exports = router
